﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;

namespace ProgNetComponents.Tools
{
    /// <summary>
    /// DTE helper class
    /// </summary>
    public static class Coding
    {
        /// <summary>
        /// Creates the bind CTX.
        /// </summary>
        /// <param name="reserved">The reserved.</param>
        /// <param name="ppbc">The PPBC.</param>
        [System.Runtime.InteropServices.DllImport("ole32.dll")]
        private static extern void CreateBindCtx(int reserved, out System.Runtime.InteropServices.ComTypes.IBindCtx ppbc);
        /// <summary>
        /// Gets the running object table.
        /// </summary>
        /// <param name="reserved">The reserved.</param>
        /// <param name="prot">The prot.</param>
        [System.Runtime.InteropServices.DllImport("ole32.dll")]
        private static extern void GetRunningObjectTable(int reserved, out System.Runtime.InteropServices.ComTypes.IRunningObjectTable prot);

        /// <summary>
        /// Gets DTE object associated with devenv process
        /// </summary>
        /// <param name="devenv">devenv.exe process</param>
        /// <returns></returns>
        public static EnvDTE.DTE GetOpenedDevenv(System.Diagnostics.Process devenv)
        {
            //rot entry for visual studio running under current process.
            string rotEntry = String.Format("^!VisualStudio\\.DTE\\..*:{0}$", devenv.Id);
            System.Runtime.InteropServices.ComTypes.IRunningObjectTable rot;
            GetRunningObjectTable(0, out rot);
            System.Runtime.InteropServices.ComTypes.IEnumMoniker enumMoniker;
            rot.EnumRunning(out enumMoniker);
            enumMoniker.Reset();
            IntPtr fetched = IntPtr.Zero;
            System.Runtime.InteropServices.ComTypes.IMoniker[] moniker = new System.Runtime.InteropServices.ComTypes.IMoniker[1];
            while (enumMoniker.Next(1, moniker, fetched) == 0)
            {
                System.Runtime.InteropServices.ComTypes.IBindCtx bindCtx;
                CreateBindCtx(0, out bindCtx);
                string displayName;
                moniker[0].GetDisplayName(bindCtx, null, out displayName);
                if (displayName.XMatch(rotEntry))
                {
                    object comObject;
                    rot.GetObject(moniker[0], out comObject);
                    return (EnvDTE.DTE)comObject;
                }
            }
            return null;
        }

    }
}
